<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>共有{{ total }}条数据</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button type="danger" @click="handleDownload">导出</el-button>
          <el-button type="primary">新增</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table :data="list" border>
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <img-tools :src="scope.row.staffPhoto || ''" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAdd(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 8, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog title="分配角色" :visible.sync="showDialog">
      <assign-role ref="AssignRole" :cur-id="curId" @close="hClose" />
    </el-dialog>
  </div>
</template>

<script>
import { TYPE_MAP } from '@/constant/Employee'
import { initEmployees, delEmployeeAPI } from '@/api/employees'
import PageTools from '@/components/PageTools/index.vue'
import AssignRole from './AssignRole.vue'
export default {
  components: { PageTools, AssignRole },
  data() {
    return {
      list: [],
      total: 0,
      page: 1,
      size: 10,
      showDialog: false,
      curId: ''
    }
  },
  created() {
    this.initEmployeesList()
  },
  methods: {
    // 子组件保存成功
    hClose() {
      this.showDialog = false
    },
    // 点击分配角色
    hAdd(id) {
      this.showDialog = true
      this.curId = id
      this.$nextTick(() => {
        this.$refs.AssignRole.getEmployee()
      })
    },
    handleSizeChange(val) {
      // console.log(val)
      this.size = val
      this.page = 1
      this.initEmployeesList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.initEmployeesList()
    },
    // 格式化表格数据
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    // 获取基本信息（渲染用）
    async initEmployeesList() {
      try {
        const res = await initEmployees({ page: this.page, size: this.size })
        console.log('', res)
        // 保存数据
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log('', err)
      }
    },
    // 删除
    async doDel(id) {
      try {
        await delEmployeeAPI(id)
        // 删除成功提示用户
        this.$message.success('删除成功')
        // 重新请求数据
        this.initEmployeesList()
        // 保存数据
      } catch (err) {
        console.log('', err)
      }
    },
    // 用户点击删除按钮
    hDel(id) {
      this.$confirm('确认删除？', '系统提示').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    // 点击了导出
    async handleDownload() {
      const res = await initEmployees({ page: this.page, size: this.size })
      // console.log('', res)
      // 这个文件初始不会加载进来，@/vendor/Export2Excel
      // 点击按钮，执行回调，就会去加载这个文件
      // .then()当文件读入完成之后，做....
      import('@/vendor/Export2Excel').then(excel => {
        // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        const { header, data } = this.formDate(res.data.rows)
        console.log(header, data)

        // 生成excel
        excel.export_json_to_excel({
          header,
          data,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx'// 生成的文件类型
        })
      })
    },
    formDate(arr) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址',
        'enableState': '账号状态'
      }
      const header = Object.keys(arr[0]).map(ele => map[ele])
      const data = arr.map(ele => {
        // console.log(ele)
        ele.formOfEmployment = TYPE_MAP[ele.formOfEmployment]
        return Object.values(ele)
      })
      return { header, data }
    }
  }
}
</script>
